import { useTranslation } from "react-i18next"
import { Divider, Link } from '@mui/material'
// import { Cached } from '@mui/icons-material';
import { useState, useCallback, useEffect, useRef, forwardRef, useImperativeHandle } from "react"
import { useLocation } from 'react-router-dom';
import { makeStyles } from 'tss-react/mui';
import TreeSelect from './TreeSelect'
import MyAutoComplete from "./MyAutoComplete"
import MyTreeViewLazy from "../../MyTreeViewLazy"
import { array2Tree, translateTree, unidimensionalList } from '../../../utils/util'
import api from "../../../api"
import message from '../../../utils/system/message'

const useStyles = makeStyles()(() => ({
  leftTreeContainer: {
    '.title': {
      padding: '12px 16px'
    }
  }
}))

/**
 * 
 * @param {*} props 
 * @returns 当页面需要使用左侧资产树时可以使用该组件
 */
const LeftTree = forwardRef(function LeftTree(props, ref) {
  useImperativeHandle(ref, () => ({
    refreshTreeData: () => refreshTreeFunc()
  }))

  const location = useLocation()
  const { classes } = useStyles()
  const { t } = useTranslation()
  const { onZoneChange, changeExpandOnLabel, cancelByClick, getClickedNodeKeys, useType, onChangeSelectedNode, autoFocusType, refreshFunc } = props
  const treeRef = useRef(null)
  const isFirst = useRef(true)

  const [selectedZoneId, setSelectedZoneId] = useState('')
  const [searchNodeId, setSearchNodeId] = useState(null)
  const [treeData, setTreeData] = useState([])
  // const [isRefreshing, setIsRefreshing] = useState(false)
  const [defaultClickNodeKeys, setDefaultClickNodeKey] = useState([])

  const getTreeDatas = useCallback(async () => {
    try {
      const zoneRes = await api.spreader.queryZone({ parentId: '' })
      if (zoneRes?.data?.length) {
        const treeData = array2Tree(zoneRes.data, null)
        if (location.state?.defaultRootId) {
          if (onChangeSelectedNode && typeof (onChangeSelectedNode) === 'function') {
            onChangeSelectedNode({ id: location.state.defaultRootId, type: 'zone' })
          }
          setSelectedZoneId(location.state.defaultRootId)
        } else {
          if (onChangeSelectedNode && typeof (onChangeSelectedNode) === 'function') {
            onChangeSelectedNode({ id: treeData[0].id, type: 'zone' })
          }
          setSelectedZoneId(treeData[0].id)
        }
        return Promise.resolve(treeData)
      }
      return Promise.resolve([])
    } catch (err) {
      console.log(err)
      return Promise.resolve([])
    }
  }, [])

  const findFirstDomByType = useCallback((treeData, type, result) => {
    if (treeData?.length) {
      for(let i = 0; i < treeData.length; i++) {
        if (result?.id && result.type === type) {
          break
        }
        if (treeData[i].id && treeData[i].type === type) {
          result = treeData[i]
          break
        } else if (treeData[i].children?.length) {
          result = findFirstDomByType(treeData[i].children, type, result)
        }
      }
    }
    return result
  }, [])

  const getTreeByArea = useCallback(async () => {
    try {
      setSearchNodeId(null)
      if (selectedZoneId) {
        const res = await api.spreader.getZoneTree({ parentId: selectedZoneId })
        if (res?.data) {
          const { childZones, ports, spreaders } = res.data
          const treeData = translateTree(childZones, ports, spreaders, useType)
          if (isFirst.current) {
            if (location.state?.defaultClickNodeKey) {
              setDefaultClickNodeKey([location.state.defaultClickNodeKey])
            } else if (autoFocusType) {
              const firstDom = findFirstDomByType(treeData, autoFocusType)
              if (firstDom?.id) {
                setDefaultClickNodeKey([firstDom.id])
              } else {
                getClickedNodeKeys && getClickedNodeKeys([])
              }
            }
            isFirst.current = false
          } else if (autoFocusType) {
            const firstDom = findFirstDomByType(treeData, autoFocusType)
            if (firstDom?.id) {
              setDefaultClickNodeKey([firstDom.id])
            } else {
              getClickedNodeKeys && getClickedNodeKeys([])
            }
          }
          setTreeData(treeData)
          return
        }
      }
      setTreeData([])
    } catch (err) {
      console.log(err)
    }
  }, [selectedZoneId, useType, autoFocusType, findFirstDomByType])

  useEffect(() => {
    getTreeByArea()
  }, [getTreeByArea])

  const rootChange = useCallback((zoneId) => {
    if (onChangeSelectedNode && typeof (onChangeSelectedNode) === 'function') {
      onChangeSelectedNode({ id: zoneId, type: 'zone' })
    }
    setSelectedZoneId(zoneId)
  }, [onChangeSelectedNode])

  useEffect(() => {
    if (onZoneChange && typeof (onZoneChange) === 'function') {
      onZoneChange(selectedZoneId)
    }
  }, [selectedZoneId])

  const getAutoCompleteOptions = useCallback(() => {
    const arr = unidimensionalList(treeData)
    return arr
  }, [treeData])

  useEffect(() => {
    if (searchNodeId) {
      setDefaultClickNodeKey([searchNodeId])
    } else {
      setDefaultClickNodeKey([])
    }
  }, [searchNodeId])

  const getCurrentHighlightNode = useCallback((nodeData) => {
    if (onChangeSelectedNode && typeof (onChangeSelectedNode) === 'function') {
      onChangeSelectedNode(nodeData)
    }
  }, [])

  const refreshTreeFunc = useCallback(async (e) => {
    try {
      if (e) {
        e.stopPropagation()
      }
      // if (!selectedZoneId) return
      const res = await api.spreader.refreshTree()
      if (res?.data) {
        if (refreshFunc && typeof(refreshFunc) === 'function') {
          refreshFunc()
        }
        message.success({ content: t('common.refreshSuccess') })
        getTreeByArea()
      } else {
        message.warning({ content: t('common.refreshFrequently') })
      }
    } catch (err) {
      console.log(err)
    }
  }, [t, getTreeByArea, refreshFunc])

  return (
    <div className={`${classes.leftTreeContainer} width-full height-full disFlex flexColumn`}>
      <div className="title">
        <Link underline="none" sx={{ textDecorationColor: 'inherit', textTransform: 'capitalize', fontWeight: 'bold' }}>{t('portManagement.assetTree')}</Link>
      </div>
      <Divider/>
      <div className="pd16 flexGrow1 height0 disFlex flexColumn">
        <TreeSelect
          value={selectedZoneId}
          label={t('portManagement.countryOrArea')}
          onChange={(zoneId) => rootChange(zoneId)}
          getTreeDatas={getTreeDatas}
          treeLabelProp='i18nName'
          // endAdornment={
          //   <InputAdornment position="end">
          //     <IconButton onClick={refreshTreeFunc}>
          //       <Cached className={`${isRefreshing ? 'rotateAni360' : ''}`}/>
          //     </IconButton>
          //   </InputAdornment>
          // }
        />
        <MyAutoComplete
          value={searchNodeId}
          className='mt16'
          focusGetOptions={true}
          valueProp='id'
          labelProp='name'
          changeValue={(node) => setSearchNodeId(node)}
          getOptions={getAutoCompleteOptions}
          innerInputLabel={t('optionsRecord.search')}
          innerInputPlaceholder={t('optionsRecord.keyToSearch')}
        />
        <div className="flexGrow1 height0">
          <MyTreeViewLazy
            ref={treeRef}
            treeData={treeData}
            changeExpandOnLabel={changeExpandOnLabel}
            cancelByClick={cancelByClick}
            getClickedNodeKeys={getClickedNodeKeys}
            getCurrentHighlightNode={getCurrentHighlightNode}
            defaultClickNodeKeys={defaultClickNodeKeys}
            className='height-full overFlowAuto positionRelative'
          />
        </div>
      </div>
    </div>
  )
})

export default LeftTree